package com.study.cloud.gateway.core.context;


import com.study.cloud.gateway.common.request.GatewayRequest;
import com.study.cloud.gateway.common.response.GatewayResponse;
import com.study.cloud.gateway.common.rule.Rule;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import lombok.Data;

/**
 * @author wangwancheng
 * @create 2025/7/17 15:39
 */
@Data
public class GatewayContext extends BaseContext{
    /**
     * 请求
     */
    private GatewayRequest request;
    /**
     * 响应
     */
    private GatewayResponse response;
    /**
     * 规则
     */
    private Rule rule;
    /**
     * 已经重试的次数
     */
    private int currentRetryTimes;

    public GatewayContext(String protocol, ChannelHandlerContext nettyCtx, boolean keepAlive,
                          GatewayRequest  request ,
                          Rule rule)
    {
        super(protocol, nettyCtx, keepAlive);
        this.request = request;
        this.rule = rule;
    }

    public String getUniqueId()
    {
        return request.getUniqueId();
    }

    /**
     * 重写父类 释放资源
     */
    public void releaseRequest()
    {
        if (requestReleased.compareAndSet(false,true)){
            ReferenceCountUtil.release(request.getFullHttpRequest());
        }
    }
}
